package com.weijx.dishes.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.weijx.dishes.config.FrontendConfig;
import com.weijx.dishes.entity.TemplateDataItem;
import com.weijx.dishes.entity.TemplateMessage;
import com.weijx.dishes.entity.Order;
import com.weijx.dishes.service.WeChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * com.weijx.dishes.service.impl.WeChatServiceImpl
 * 描述：
 * on 2025/11/5-下午5:08
 *
 * @author weijx
 */


@Service
public class WeChatServiceImpl implements WeChatService {

    private static final Logger log = LoggerFactory.getLogger(WeChatServiceImpl.class);

    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.appsecret}")
    private String appSecret;

    @Value("${wechat.template.order_status_id}")
    private String orderTemplateId;

    @Resource
    private FrontendConfig frontendConfig;

    // 内存缓存access_token
    private final Map<String, String> tokenCache = new ConcurrentHashMap<>();
    private final Map<String, Long> tokenExpiryTime = new ConcurrentHashMap<>();

    private void sendOrderStatusUpdate(String toUserOpenId, String first, String keyword1, String keyword2, String keyword3, String keyword4, String remark, String url) {
        try {
            String accessToken = getAccessToken();
            String apiUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;

            Map<String, TemplateDataItem> data = new HashMap<>();
            data.put("first", new TemplateDataItem(first));
            data.put("keyword1", new TemplateDataItem(keyword1));
            data.put("keyword2", new TemplateDataItem(keyword2));
            data.put("keyword3", new TemplateDataItem(keyword3));
            data.put("keyword4", new TemplateDataItem(keyword4));
            data.put("remark", new TemplateDataItem(remark));

            TemplateMessage message = new TemplateMessage(toUserOpenId, orderTemplateId, url, data);
            String jsonMessage = JSON.toJSONString(message);

            log.info("准备发送模板消息 (最终版): {}", jsonMessage);
            String response = HttpUtil.post(apiUrl, jsonMessage);
            log.info("模板消息发送结果 (最终版): {}", response);

        } catch (Exception e) {
            log.error("发送模板消息失败", e);
        }
    }

    private String getAccessToken() {
        String accessToken = tokenCache.get("accessToken");
        Long expiryTime = tokenExpiryTime.get("expiryTime");

        if (accessToken != null && System.currentTimeMillis() < expiryTime) {
            return accessToken;
        }

        String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appId, appSecret);
        String response = HttpUtil.get(url);
        JSONObject json = JSON.parseObject(response);

        if (json.containsKey("access_token")) {
            accessToken = json.getString("access_token");
            long newExpiryTime = System.currentTimeMillis() + (json.getLong("expires_in") - 300) * 1000;
            tokenCache.put("accessToken", accessToken);
            tokenExpiryTime.put("expiryTime", newExpiryTime);
            log.info("成功获取新的AccessToken");
            return accessToken;
        } else {
            log.error("获取AccessToken失败: {}", response);
            throw new RuntimeException("获取微信AccessToken失败: " + json.getString("errmsg"));
        }
    }

    @Override
    public void sendOrderNotificationToHandler(Order order) {

        String first = "您有一个新的订单需要处理！";
        String keyword1 = order.getCustomerName();
        String keyword2 = order.getOrderDetails().stream()
                .map(detail -> detail.getProductName() + "x" + detail.getQuantity())
                .collect(Collectors.joining(", "));
        String keyword3 = (order.getNote() != null && !order.getNote().isEmpty()) ? order.getNote() : "无";
        String keyword4 = "待接单";
        String remark = "请尽快处理。点击本消息可直接进入处理页面。";
        String processUrl = frontendConfig.getProcessUrl(order.getId());

        // [核心修改] 使用 order.getHandlerOpenId()
        sendOrderStatusUpdate(order.getHandlerOpenId(), first, keyword1, keyword2, keyword3, keyword4, remark, processUrl);
    }

    @Override
    public void sendProcessResultToCustomer(Order order) {
        String first = "亲爱的" + order.getCustomerName() + "，您的订单状态更新啦！";

        String keyword1 = order.getCustomerName();

        String keyword2 = order.getOrderDetails().stream()
                .map(detail -> detail.getProductName() + "x" + detail.getQuantity())
                .collect(Collectors.joining(", "));

        String keyword3 = (order.getProcessNote() != null && !order.getProcessNote().isEmpty()) ? order.getProcessNote() : "店家爱心满满，没有备注哦~";

        String keyword4; // 状态
        if (order.getOrderStatus() == 1) {
            keyword4 = "✅ 已完成，快来取餐吧！";
        } else if (order.getOrderStatus() == 2) {
            keyword4 = "❌ 已驳回";
        } else {
            return;
        }

        String remark = "感谢您的下单，爱你哟！💖";

        sendOrderStatusUpdate(order.getCustomerOpenId(), first, keyword1, keyword2, keyword3, keyword4, remark, null);
    }

}
